#!/usr/bin/env python
"""
This is a simple example of building and running a simulation
using Box2D. Here we create a large ground box and a small dynamic box.
"""
 
import pyglet, random
from Box2D import *

window = pyglet.window.Window()
#sprite = pyglet.sprite.Sprite(image)
rain_img = pyglet.image.load('rain.png')
rain_img.anchor_x = rain_img.width // 2
rain_img.anchor_y = rain_img.height // 2
 
# Define the size of the world. Simulation will still work
# if bodies reach the end of the world, but it will be slower.
worldAABB=b2AABB()
worldAABB.lowerBound = (-100, -100)
worldAABB.upperBound = (100, 100)
 
# Define the gravity vector.
gravity = b2Vec2(0, -10)
 
# Do we want to let bodies sleep?
doSleep = True
 
# Construct a world object, which will hold and simulate the rigid bodies.
world = b2World(worldAABB, gravity, doSleep)
 
# Define the ground body.
groundBodyDef = b2BodyDef()
groundBodyDef.position.Set(0, 0)
 
# Call the body factory which allocates memory for the ground body
# from a pool and creates the ground box shape (also from a pool).
# The body is also added to the world.
groundBody = world.CreateBody(groundBodyDef)
 
# Define the ground box shape.
groundShapeDef = b2PolygonDef()
 
# The extents are the half-widths of the box.
groundShapeDef.SetAsBox(300, .025)
 
# Add the ground shape to the ground body.
groundShapeDef.filter.categoryBits   = 0x0002
groundShapeDef.filter.maskBits       = 0x0004
groundBody.CreateShape(groundShapeDef)

# Prepare for simulation. Typically we use a time step of 1/60 of a
# second (60Hz) and 10 iterations. This provides a high quality simulation
# in most game scenarios.
timeStep = 1.0 / 60
iterations = 10

bodies = []

batch = pyglet.graphics.Batch()
sprites = []
class MyBoundaryListener(b2BoundaryListener):
    def __init__(self):
        super(MyBoundaryListener, self).__init__()
    def Violation(self, body):
        print "ERROR!"
        myActor = body.userData['actor'] # if you stored it as a dict
        myActor.MarkForErrorHandling()
        
class MyDestructionListener(b2DestructionListener):
    def __init__(self):
        super(MyDestructionListener, self).__init__()
    def SayGoodbye(self, joint):
        # remove all references to joint.
        print "REMOVE REFERENCES!"
        pass
myDestructionListener = MyDestructionListener()
world.SetDestructionListener(myDestructionListener)
myBoundaryListener = MyBoundaryListener()
world.SetBoundaryListener(myBoundaryListener)
def update(dt):
    vel_iters, pos_iters = 10, 8
    world.Step(timeStep, vel_iters, pos_iters)
    for x in range(5):
        # Define the dynamic body. We set its position and call the body factory.
        bodyDef = b2BodyDef()
        
        bodyDef.position.Set(random.randrange(2000) / 100., 600/50.)
        body = world.CreateBody(bodyDef)
        
        # Define another box shape for our dynamic body.
        shapeDef = b2PolygonDef()
        shapeDef.SetAsBox(.2, .2)
         
        # Set the box density to be non-zero, so it will be dynamic.
        shapeDef.density = 1
         
        # Override the default friction.
        shapeDef.friction = 0.3
        # Add the shape to the body.
        shapeDef.filter.categoryBits  = 0x0004
        shapeDef.filter.maskBits      = 0x0002
        body.CreateShape(shapeDef)
         
        # Now tell the dynamic body to compute it's mass properties base on its shape.
        body.SetMassFromShapes()
        bodies.append(body)#TODO: get rid of this if you're not using it!
        sprites.append(pyglet.sprite.Sprite(rain_img, batch=batch))
        
@window.event
def on_draw():
    
    window.clear()
    for i, body in enumerate(bodies):
        sprites[i].x = body.position.x * 50
        sprites[i].y = body.position.y * 50
    batch.draw()
    
pyglet.clock.schedule_interval(update, timeStep)
pyglet.app.run()
